package com.evan.review.architecture.components;

import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import com.evan.review.R;

/**
 * Lifecycle示例Activity
 * 展示Lifecycle组件的基本用法
 */
public class LifecycleExampleActivity extends AppCompatActivity {

    private TextView tvLifecycleState;
    private TextView tvLifecycleEvents;
    private StringBuilder eventsLog = new StringBuilder();
    private MyLifecycleObserver lifecycleObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lifecycle_example);

        // 设置标题
        setTitle("Lifecycle示例");

        // 初始化视图
        initViews();

        // 创建并添加生命周期观察者
        lifecycleObserver = new MyLifecycleObserver();
        getLifecycle().addObserver(lifecycleObserver);

        // 更新当前状态
        updateCurrentState();
    }

    private void initViews() {
        tvLifecycleState = findViewById(R.id.tv_lifecycle_state);
        tvLifecycleEvents = findViewById(R.id.tv_lifecycle_events);

        // 清除日志按钮
        Button btnClearLog = findViewById(R.id.btn_clear_log);
        btnClearLog.setOnClickListener(v -> {
            eventsLog.setLength(0);
            tvLifecycleEvents.setText("生命周期事件日志：");
        });

        // 触发对话框按钮（会导致onPause）
        Button btnShowDialog = findViewById(R.id.btn_show_dialog);
        btnShowDialog.setOnClickListener(v -> {
            showSimpleDialog();
        });

        // 触发后台按钮（会导致onStop）
        Button btnGoBackground = findViewById(R.id.btn_go_background);
        btnGoBackground.setOnClickListener(v -> {
            moveTaskToBack(true);
        });
    }

    private void showSimpleDialog() {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("生命周期测试")
                .setMessage("打开此对话框将触发onPause事件")
                .setPositiveButton("确定", null)
                .show();
    }

    private void updateCurrentState() {
        Lifecycle.State currentState = getLifecycle().getCurrentState();
        tvLifecycleState.setText("当前状态: " + currentState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateCurrentState();
    }

    @Override
    protected void onPause() {
        super.onPause();
        updateCurrentState();
    }

    @Override
    protected void onStop() {
        super.onStop();
        updateCurrentState();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 不需要手动移除观察者，Lifecycle会自动处理
    }

    /**
     * 自定义Lifecycle观察者
     */
    private class MyLifecycleObserver implements LifecycleEventObserver {

        @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
            // 记录生命周期事件
            eventsLog.append(event.toString()).append("\n");
            tvLifecycleEvents.setText("生命周期事件日志：\n" + eventsLog.toString());

            // 根据不同的生命周期事件执行不同的操作
            switch (event) {
                case ON_CREATE:
                    logEvent("组件创建");
                    break;
                case ON_START:
                    logEvent("组件可见");
                    break;
                case ON_RESUME:
                    logEvent("组件获得焦点，可交互");
                    break;
                case ON_PAUSE:
                    logEvent("组件失去焦点");
                    break;
                case ON_STOP:
                    logEvent("组件不可见");
                    break;
                case ON_DESTROY:
                    logEvent("组件销毁");
                    break;
                case ON_ANY:
                    // 不处理
                    break;
            }
        }

        private void logEvent(String message) {
            // 在实际应用中，这里可以执行与生命周期相关的操作
            // 例如：启动/停止网络请求，释放资源等
        }
    }


    // 反射的方式创建生命周期观察者 因此抛弃了
    public class MyObserver implements LifecycleObserver {
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        public void onCreate() {
            // 处理创建事件
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        public void onDestroy() {
            // 处理销毁事件
        }
    }


    public static class MyObserver2 implements DefaultLifecycleObserver {
        @Override
        public void onCreate(@NonNull LifecycleOwner owner) {
            DefaultLifecycleObserver.super.onCreate(owner);
        }

        @Override
        public void onDestroy(@NonNull LifecycleOwner owner) {
            DefaultLifecycleObserver.super.onDestroy(owner);
        }

        @Override
        public void onPause(@NonNull LifecycleOwner owner) {
            DefaultLifecycleObserver.super.onPause(owner);
        }

        @Override
        public void onResume(@NonNull LifecycleOwner owner) {
            DefaultLifecycleObserver.super.onResume(owner);
        }

        @Override
        public void onStart(@NonNull LifecycleOwner owner) {
            DefaultLifecycleObserver.super.onStart(owner);
        }

        @Override
        public void onStop(@NonNull LifecycleOwner owner) {
            DefaultLifecycleObserver.super.onStop(owner);
        }
    }

} 